/*
 * Created by SharpDevelop.
 * User: Dror B. Helper
 * Date: 29/09/2008
 * Time: 14:21
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;

namespace StackOverflowClient
{
    /// <summary>
    /// Description of HttpWebRequestExtension.
    /// </summary>
    public static class HttpWebRequestExtension
    {
        public static string GetStringFromURL(string urlString, IWebProxy proxy)
        {
            var dataRequest = (HttpWebRequest)WebRequest.Create(urlString);
            dataRequest.Timeout = 15000;
           
            dataRequest.Proxy = proxy;

            dataRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");

            using (var dataResponse = (HttpWebResponse)dataRequest.GetResponse())
            {
                var responseStream = dataResponse.GetResponseStream();

                if (dataResponse.ContentEncoding.ToLower().Contains("gzip"))
                {
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                }
                else if (dataResponse.ContentEncoding.ToLower().Contains("deflate"))
                {
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                }

                var Reader = new StreamReader(responseStream, Encoding.Default);
                var result = Reader.ReadToEnd();

                responseStream.Close();

                return result;
            }


            /*
            var enc  = Encoding.UTF8;
            using(var responseStream = new StreamReader(dataResponse.GetResponseStream(), enc))
            {
                return responseStream.ReadToEnd();
            }
             */
        }

    }
}
